package net.maku.system.erp.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import net.maku.framework.common.constant.Constant;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.system.erp.convert.SysMeasureUnitConvert;
import net.maku.system.erp.dao.SysMeasureUnitDao;
import net.maku.system.erp.entity.SysMeasureUnitEntity;
import net.maku.system.erp.query.SysMeasureUnitQuery;
import net.maku.system.erp.vo.SysMeasureUnitVO;
import net.maku.system.erp.service.SysMeasureUnitService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 计量单位管理表
 *
 * @author 王宝林 baolin.wang@aliyun.com
 * @since 1.0.0 2024-03-19
 */
@Service
@AllArgsConstructor
public class SysMeasureUnitServiceImpl extends BaseServiceImpl<SysMeasureUnitDao, SysMeasureUnitEntity> implements SysMeasureUnitService {

    @Override
    public PageResult<SysMeasureUnitVO> page(SysMeasureUnitQuery query) {

        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<SysMeasureUnitEntity> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<SysMeasureUnitEntity> list = baseMapper.getList(params);
        List<SysMeasureUnitVO> respData = SysMeasureUnitConvert.INSTANCE.convertList(list);
        return new PageResult<>(respData, page.getTotal());
    }

    private LambdaQueryWrapper<SysMeasureUnitEntity> getWrapper(SysMeasureUnitQuery query){
        LambdaQueryWrapper<SysMeasureUnitEntity> wrapper = Wrappers.lambdaQuery();

        return wrapper;
    }

    @Override
    public void save(SysMeasureUnitVO vo) {
        SysMeasureUnitEntity entity = SysMeasureUnitConvert.INSTANCE.convert(vo);
        baseMapper.insert(entity);
    }

    @Override
    public void update(SysMeasureUnitVO vo) {
        try{
            SysMeasureUnitEntity entity = SysMeasureUnitConvert.INSTANCE.convert(vo);
            updateById(entity);
        } catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    private Map<String, Object> getParams(SysMeasureUnitQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", query.getCode());
        params.put("name", query.getName());
        params.put("unitGroup", query.getUnitGroup());
        params.put("description", query.getDescription());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null));

        return params;
    }
}